package com.mall.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * Sentinel限流配置
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class SentinelConfig {
    
    private final ObjectMapper objectMapper;
    
    @PostConstruct
    public void init() {
        initBlockRequestHandler();
    }
    
    /**
     * 自定义限流异常处理
     */
    private void initBlockRequestHandler() {
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {
                String path = exchange.getRequest().getURI().getPath();
                log.error("API网关限流：{}", path);
                
                Map<String, Object> result = new HashMap<>();
                result.put("code", HttpStatus.TOO_MANY_REQUESTS.value());
                result.put("message", "请求频率过高，请稍后再试");
                result.put("path", path);
                result.put("success", false);
                
                try {
                    return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                            .contentType(MediaType.APPLICATION_JSON)
                            .bodyValue(objectMapper.writeValueAsString(result));
                } catch (JsonProcessingException e) {
                    log.error("限流响应异常", e);
                    return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                            .contentType(MediaType.APPLICATION_JSON)
                            .bodyValue("{\"code\":429,\"message\":\"请求频率过高\"}");
                }
            }
        };
        
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }
} 